<?php
/*
 * 订单详情
 */
namespace Mobile\Controller;

use Mobile\Model\orderModel;
use Mobile\Controller\PaywechatController;

class OrderdetailController extends BaseController {

    public $orderModel;
    public $payModel;

    public function __construct() {
        parent::__construct();
        $this->orderModel = new orderModel();
        $this->payModel = M('pay');
    }
    

    /*
     * 生成微信支付信息
     * 1订单,2充值
     */
    protected function _get_wechatpay($order){
        
        $notify_url = get_domain()."/mobile/ordercallback/callback/order_id/".$order['order_id'];// 异步通知地址
    
        $wechatpay = new PaywechatController();
        $wechatpay->setParameter("notify_url", $notify_url);//通知URL
        $wechatpay->setParameter("body", "订单:".$order['order_sn']);//商品描述
        $wechatpay->setParameter("out_trade_no", $order['order_sn']);//商户订单号
        $wechatpay->setParameter("total_fee", $order['pay_money']*100);//订单总金额,单位为分
        $wechatpay->setParameter("spbill_create_ip", $order['order_ip']?$order['order_ip']:get_client_ip());//客户ip地址
        $wechatpay->setParameter("openid","$this->openid");//
        $wechatpay->setParameter("trade_type","JSAPI");//
        $jsApiParameters = $wechatpay->getPayCode();
    
        return $jsApiParameters;
    }
    
    /*
     * 获取物流信息
     */
    protected function _get_wuliuinfo($order){
        //0待支付,1已付款,,2完成,3.待退款 4已退款,5发货,0未完成,6订单关闭,
        //查询快递信息
        $elong = strlen($order['express_no']);
        if($elong>6){
            //查询物流信息
            $wuliu = wuliu($order['express_no'], $order['express']);
            //http://www.aikuaidi.cn/api/
    
            $status = array(
                0 => '<span style="color:red;">无记录</span>',
                1 => '<span style="color:red;">未录单</span>',
                2 => '<span style="color:green;">在途中</span>',
                3 => '<span style="color:green;">派送中</span>',
                4 => '<span style="color:green;">已签收</span>',
                5 => '<span style="color:red;">拒收</span>',
                6 => '<span style="color:red;">疑难件</span>',
                7 => '<span style="color:red;">退回</span>',
            );
    
            $status = $status[$wuliu['status']];//结果状态
            $this->assign("wuliu_status",$status);
    
            if($wuliu['errCode'] == 0){
                $this->assign("wuliu_res",$wuliu['data']);
            }
        }
    
        return true;
    }
    
    //获取订单支付状态文字
    //TODO 货到付款
    //0待支付,1已付款,,2完成,3.待退款 4已退款,5发货,0未完成,6订单关闭,
    protected function _order_status($stutus=0){
        $status_arr = array(
            "待付款","待发货","已完成","待退款","已退款","待收货","已关闭"
        );
        return $status_arr[$stutus];
    }



    /*
     * 订单详情
     */
    public function index(){
        //parent::wxLogin();
        $seo_data = array(
            "title" => $this->lang['order_detail'],
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        
        $order_id = get('order_id');
        if(!$order_id){
            $this->error2("参数错误","/mobile/index");//TODO
        }
        
        $where = array(
            "order_id" => $order_id,
            "uid" => $this->uid
        );
        //查找订单
        $order = $this->orderModel->getOrder($where);
        if(empty($order)){
            $this->error2("订单不存在,请检查","/mobile/index");//TODO
        }
        
        $order['status'] = $this->_order_status($order['checked']);//获取订单支付状态文字
        
        $order['delivery'] = unserialize($order['delivery']);//反序列化
        $order['goods'] = unserialize($order['goods']);//反序列化
        
        //准备微信支付信息
        if($order['checked'] == 0){
            //待支付
            
            $jsApiParameters = $this->_get_wechatpay($order,$type=1);
            $this->assign("jsApiParameters",$jsApiParameters);
            
        }else if(in_array($order['checked'],array(2,5))){
            //已经发货的,获取物流信息
            $this->_get_wuliuinfo($order);
        }
        
        $banklist = M('bankcom')->where(array('is_wangyin'=>1))->select();
        foreach ($banklist as $k=>$bank) {
            $banklist[$k]['ecom_bianhao'] = strtolower($banklist[$k]['ecom_bianhao']);
        }
        $this->assign('banklist',$banklist);
        
        
        $this->setShare();
        
        $this->assign("order",$order);
        $this->display();
    }
    
    
    public function cardpay(){
        $this->display();
    }
    
    
    
    public function chuxucardpay(){
        if(IS_AJAX){
            $allow = array('card_num','mobile','card_code','name','id_code');
            $data = param_filter($_POST, $allow);
            _pr($data);
        }
        $this->display();
    }
    
    /*
     * 检查支付状态
     * 0待支付,1已付款,,2完成,3.待退款 4已退款,5发货,6订单关闭
     */
    public function checkpay(){
        $order_id = get('order_id');
        $where = array(
            "order_id" => $order_id
        );
        $order = $this->orderModel->getOrder($where);
        if(in_array($order['checked'],array(1,2,3,4,5))){
            return_json(1,"当前订单已经支付成功,无需重复支付","","/mobile/orderdetail?order_id=".$order_id);
        }
        if(in_array($order['checked'],array(6))){
            return_json(1,"当前订单已关闭,不能继续支付","","/mobile/orderdetail?order_id=".$order_id);
        }
    
        return_json(0,"请稍后...");
    
    }
    
    
    public function alipay($id = ''){
        if($id){
            $order_id = $id;
        }else{
            $order_id = get('order_id');
        }
        
        $order = $this->orderModel->where(array('order_id'=>$order_id))->find();
        $alipay = new PayaliwapController();
        $data['notify_url'] = get_domain().'/mobile/ordercallback/alipaycallback/order_id/'.$order_id;//异步通知
        
        $data['return_url'] = get_domain().'/mobile/orderdetail/index/order_id/'.$order_id;//同步通知
        
        //用户付款中途退出返回商户网站的地址
        $data['show_url'] = get_domain().'/mobile/orderdetail/index/order_id/'.$order_id;
        
        $data['out_trade_no'] = $order['order_sn'];//商城订单号
        $data['subject'] = '订单'.$order['order_sn'];//商品名称
        // $data['body'] = '';//商品描述
        $data['total_fee'] = $order['pay_money'];//交易金额

            
        if(IS_AJAX) {
            if($order['checked']!=0) {
                return_json(1,'订单已支付');
            }

            $apppay = $alipay->tradeAppPay($order);
            return_json(0,'',$apppay);
        }else{
            if($order['checked']!=0) {
                $this->error2('改订单已支付');
            }
            $url = $alipay->wappay($data);
        }

        
        if($id){
            return $url;
        }else{
            $this->assign('alipay_url',$url);
            $this->display();
        }
        
        
    }
    
    /*
     * 二维码
     */
    public function qrcodeapi(){
        $order_id = get('order_id');
        $text = $this->alipay($order_id);
        if($text){
            qrcode($text, false, $level = 1, $size = 8, $margin = 1,$saveandprint=false);
        }
    }
    /*
     * 接收信用卡信息并发起创建订单获取hm订单号
     */
    public function nocardPayCreate(){
        if(!IS_AJAX){
            return_json(1,'非法提交');
        }
        $order_sn = get('order_sn');
        $order = $this->orderModel->where(array('order_sn'=>$order_sn))->find();
        $allow = array('cardno','phone','cardtype','validthru','cvv2','name','idcard');
        $cardinfo = param_filter($_POST, $allow);
        $this->_checkData($cardinfo);
        $pay = new PayhmController();
        $res = $pay->noCardCreateOrder($order,$cardinfo);
       
        if($res){
           /*  $data = array(
                "out_trade_no" => $res['orderid'],//返回的银行订单号
            ); */
            $orderid = $res['out_trade_no'];
            $this->orderModel->where(array('order_sn'=>$order_sn))->setField('transaction_id',$orderid);
            $this->_addOrder($orderid,$order);
            return_json(0,'提交成功,请填写验证码',$orderid);
        }else{
            return_json(1,'获取失败',$orderid);
        }
    }
    /*
     * 接收用户提交的订单号和验证码并发起支付
     */
    public function nocardPay(){
        if(!IS_AJAX){
            return_json(1,'非法提交');
        }
        $orderid = get('orderid');
        $validatecode = get('validatecode');
        if(!$validatecode){
            return_json(1,'请填写验证码');
        }
        $pay_data = array(
            'orderid' => $orderid,
            'validatecode' => $validatecode
        );
        $pay = new PayhmController();
        $res = $pay->noCardPay($pay_data);
        if($res){
            $order = $this->orderModel->where(array('transaction_id'=>$orderid))->find();
            $callback = new OrdercallbackController();
            $callback->_changeOrder($order, 4);
            return_json(0,'支付成功','','/mobile/orderlists');
        }else{
            return_json(1,'支付失败','','/mobile/orderlists');
        }
    }
    
    
    protected function _checkData($data){
        if($data['cardtype']==00){
            if(!$data['validthru']){
                return_json(1,'请输入有效期');
            }
            if(!$data['cvv2']){
                return_json(1,'请输入鉴权码');
            }
        }
        if(!$data['cardno']){
            return_json(1,'请输入卡号');
        }
        if(!$data['name']){
            return_json(1,'请输入姓名');
        }
        if(!$data['phone']){
            return_json(1,'请输入手机号');
        }
        if(!$data['idcard']){
            return_json(1,'请输入身份证号');
        }
       
    }
    
    protected function _addOrder($orderid,$order){
        $data = array(
            'uid' => $order['uid'],
            //'code_url' => $res['code_url'],
            'out_trade_no' => $orderid,
            'order_sn' => $order['order_sn'],
            'order_id' => $order['order_id'],
            'pay_type' => 4,
            'create_time' => date("Y-m-d H:i:s"),
            //'expired_time' => date("Y-m-d H:i:s",strtotime('+3600 second')),
        );
        $this->payModel->add($data);
    }
    
    public function wangyinpay() {
        $allow = $must = array(
            'bankflag','bank','order_id'
        );
        $data = param_filter($_GET, $allow,$must);
        if(!$data){
            $this->error('参数错误');
        }
        $pay = new PayhmController();
        $order = $this->orderModel->where(array('order_id'=>$data['order_id']))->find();
        if(!$order) {
            if($data){
                $this->error('订单不存在');
            }
            if($order['checked']!=0){
                $this->error('订单非未付款状态');
            }
        }
        $bank = M('bankcom')->where(array('eid'=>$data['bank']))->find();
        if(!$bank){
            $this->error('不支持该银行');
        }
        $bank['bankflag'] = $data['bankflag'];
        
        $saveData = array(
            'bank_id' => $data['bank'],
            'bank_flag' => $data['bankflag']
        );
        $this->orderModel->where(array('order_id'=>$data['order_id']))->save($saveData);
        
        $pay->wgPay($order,$bank);
    }
    
}